<template>
  <div>
    <el-container>
      <el-header>
        <h2>
          <b>管理员管理</b>
        </h2>
      </el-header>
      <el-main>
        <el-form :inline="true" :model="admin" ref="admin" class="demo-form-inline" align="center">
          <el-form-item label="管理员名称" prop="account">
            <el-input v-model="admin.account" placeholder="管理员名称"></el-input>
          </el-form-item>
          <el-form-item label="创建时间" prop="createDate">
            <span class="demonstration"></span>
            <el-date-picker
              v-model="admin.createDate"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd hh:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <el-select
              v-model="admin.roleId"
              multiple
              collapse-tags
              style="margin-left: 20px;"
              placeholder="请选择角色"
            >
              <el-option
                :label="role.name"
                :value="role.id"
                v-for="(role,index) in roles"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="admin.status" placeholder="请选择状态">
              <el-option label="全部" value="0"></el-option>
              <el-option label="正常" value="1"></el-option>
              <el-option label="冻结" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="page=1;onSubmit()">查询</el-button>
            <el-button @click="resetForm('admin')">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="tData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" :selectable="selectable"></el-table-column>
          <el-table-column label="序号" type="index" width="50"></el-table-column>
          <el-table-column prop="account" label="账号" width="130"></el-table-column>
          <el-table-column prop="roleId" label="身份" width="100" :formatter="formatRole"></el-table-column>
          <el-table-column prop="createDate" label="创建时间" width="160"></el-table-column>
          <el-table-column prop="lastLogin" label="上次登录时间" width="160"></el-table-column>
          <el-table-column prop="lastIp" label="上次登录IP" width="160"></el-table-column>
          <el-table-column prop="lockTime" label="锁定时间" width="160"></el-table-column>
          <el-table-column prop="status" label="状态" width="80" :formatter="formatStatus"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row)"
                type="primary"
                size="mini"
                v-if="scope.row.id!=1"
              >编辑</el-button>
              <el-button
                @click="changeStatus(scope.row)"
                type="danger"
                size="mini"
                v-if="scope.row.status==1&&scope.row.id!=1"
              >冻结</el-button>
              <el-button
                @click="changeStatus(scope.row)"
                type="success"
                size="mini"
                v-if="scope.row.status==2&&scope.row.id!=1"
              >解冻</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br />
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalNum"
          :page-size="3"
          align="center"
          :current-page="page"
          @current-change="handleCurrentChange"
        ></el-pagination>
        <br />
        <div align="center">
          <el-button type="danger" @click="delAll">批量冻结</el-button>
          <el-button type="primary" @click="dialogFormVisibleAdd=true">增加</el-button>
          <el-button type="success" @click="unDelAll">批量解冻</el-button>
        </div>
      </el-main>
    </el-container>

    <el-dialog
      title="管理员添加"
      :visible.sync="dialogFormVisibleAdd"
      :modal="false"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form :model="form" ref="form" :rules="formrules">
        <el-form-item label="账号" :label-width="formLabelWidth" prop="account">
          <el-input v-model="form.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="repassword">
          <el-input v-model="form.repassword"></el-input>
        </el-form-item>
        <el-form-item label="身份" :label-width="formLabelWidth" prop="roleId">
          <el-select v-model="form.roleId">
            <el-option
              :label="role.name"
              :value="role.id"
              v-for="(role,index) in roles"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose('form')">取 消</el-button>
        <el-button type="primary" @click="add('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="管理员修改"
      :visible.sync="dialogFormVisibleUpdate"
      :modal="false"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form :model="updateform" ref="updateform" :rules="updaterules">
        <el-form-item label="账号" :label-width="formLabelWidth" prop="account">
          <el-input v-model="updateform.account" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="updateform.password"></el-input>
        </el-form-item>
        <el-form-item label="身份" :label-width="formLabelWidth" prop="roleId">
          <el-select v-model="updateform.roleId">
            <el-option
              :label="role.name"
              :value="role.id"
              v-for="(role,index) in roles"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose('updateform')">取 消</el-button>
        <el-button type="primary" @click="update('updateform')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Axios from "axios";
import Qs from "qs";
export default {
  data() {
    var validateRePwd = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      admin: {
        account: "",
        roleId: "",
        createDate: "",
        status: "",
      },
      form: {
        account: "",
        password: "",
        repassword: "",
        roleId: "",
      },
      updateform: {
        id: "",
        account: "",
        password: "",
        roleId: "",
      },
      updaterules: {
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        roleId: [{ required: true, message: "请选择身份", trigger: "change" }],
      },
      formrules: {
        account: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { max: 15, message: "最多15个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        repassword: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
          { validator: validateRePwd, trigger: "blur" },
        ],
        roleId: [{ required: true, message: "请选择身份", trigger: "change" }],
      },
      roles: [],
      tData: [],
      multipleSelection: [],
      totalNum: 0,
      page: 1,
      dialogFormVisibleAdd: false,
      dialogFormVisibleUpdate: false,
      formLabelWidth: "120px",
    };
  },
  created() {
    Axios.get("/tfss/admin/role/list").then((r) => {
      if (r.data.code == 200) {
        this.roles = r.data.data;
        this.onSubmit();
      } else if (r.data.code == 403) {
        this.$message.error("没有权限");
      } else if (r.data.code == 703) {
        this.$message.error("未登录");
      } else if (r.data.code == 500) {
        this.$message.error("系统繁忙，请稍后再试");
      } else if (r.data.code == 704) {
        this.$message.error("登录失效，请重新登录");
      }
    });
  },
  methods: {
    onSubmit() {
      Axios.get("/tfss/admin/listByPage", {
        params: {
          account: this.admin.account,
          roleId: this.admin.roleId,
          createDate: this.admin.createDate,
          status: this.admin.status,
          page: this.page,
        },
        paramsSerializer: (params) => {
          return Qs.stringify(params, { indices: false });
        },
      }).then((r) => {
        if (r.data.code == 200) {
          this.tData = r.data.data.records;
          this.totalNum = r.data.data.total;
        } else if (r.data.code == 403) {
          this.$message.error("没有权限");
        } else if (r.data.code == 703) {
          this.$message.error("未登录");
        } else if (r.data.code == 500) {
          this.$message.error("系统繁忙，请稍后再试");
        } else if (r.data.code == 704) {
          this.$message.error("登录失效，请重新登录");
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    onClose(formName) {
      this.$refs[formName].resetFields();
      this.dialogFormVisibleAdd = false;
      this.dialogFormVisibleUpdate = false;
    },
    add(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm("确认增加?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              Axios.post("/tfss/admin/add", this.form).then((r) => {
                if (r.data.code === 200) {
                  this.$message({
                    type: "success",
                    message: "增加成功!",
                  });
                  this.dialogFormVisibleAdd = false;
                  this.onSubmit();
                } else if (r.data.code == 403) {
                  this.$message.error("没有权限");
                } else if (r.data.code == 703) {
                  this.$message.error("未登录");
                } else if (r.data.code == 500) {
                  this.$message.error("系统繁忙，请稍后再试");
                } else if (r.data.code == 704) {
                  this.$message.error("登录失效，请重新登录");
                } else if (r.data.code == 705) {
                  this.$message.error("账号已存在");
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消",
              });
            });
        } else {
          return false;
        }
      });
    },
    update(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm("确认修改?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              Axios.post("/tfss/admin/update", this.updateform).then((r) => {
                if (r.data.code === 200) {
                  this.$message({
                    type: "success",
                    message: "修改成功!",
                  });
                  this.dialogFormVisibleUpdate = false;
                  this.onSubmit();
                } else if (r.data.code == 403) {
                  this.$message.error("没有权限");
                } else if (r.data.code == 703) {
                  this.$message.error("未登录");
                } else if (r.data.code == 500) {
                  this.$message.error("系统繁忙，请稍后再试");
                } else if (r.data.code == 704) {
                  this.$message.error("登录失效，请重新登录");
                } else if (r.data.code == 705) {
                  this.$message.error("账号已存在");
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消",
              });
            });
        } else {
          return false;
        }
      });
    },
    handleClick(row) {
      this.dialogFormVisibleUpdate = true;
      this.updateform = JSON.parse(JSON.stringify(row));
      this.updateform.password = "";
    },
    changeStatus(row) {
      this.$confirm("确认继续操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          Axios.get("/tfss/admin/changeStatus", {
            params: {
              id: row.id,
            },
          }).then((r) => {
            if (r.data.code == 200) {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.onSubmit();
            } else if (r.data.code == 403) {
              this.$message.error("没有权限");
            } else if (r.data.code == 703) {
              this.$message.error("未登录");
            } else if (r.data.code == 500) {
              this.$message.error("系统繁忙，请稍后再试");
            } else if (r.data.code == 704) {
              this.$message.error("登录失效，请重新登录");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    delAll() {
      this.$confirm("此操作将冻结所有已选择管理员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          for (const row of this.multipleSelection) {
            if (row.status == "1") {
              Axios.get("/tfss/admin/changeStatus", {
                params: {
                  id: row.id,
                },
              }).then((r) => {
                if (r.data.code == 200) {
                  this.$message({
                    type: "success",
                    message: row.account + "冻结成功!",
                  });
                  this.onSubmit();
                } else if (r.data.code == 403) {
                  this.$message.error("没有权限");
                } else if (r.data.code == 703) {
                  this.$message.error("未登录");
                } else if (r.data.code == 500) {
                  this.$message.error("系统繁忙，请稍后再试");
                } else if (r.data.code == 704) {
                  this.$message.error("登录失效，请重新登录");
                }
              });
            } else {
              this.$message.warning(row.account + "已为冻结状态");
            }
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    unDelAll() {
      this.$confirm("此操作将解冻所有已选择管理员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          for (const row of this.multipleSelection) {
            if (row.status == "2") {
              Axios.get("/tfss/admin/changeStatus", {
                params: {
                  id: row.id,
                },
              }).then((r) => {
                if (r.data.code == 200) {
                  this.$message({
                    type: "success",
                    message: row.account + "解冻成功!",
                  });
                  this.onSubmit();
                } else if (r.data.code == 403) {
                  this.$message.error("没有权限");
                } else if (r.data.code == 703) {
                  this.$message.error("未登录");
                } else if (r.data.code == 500) {
                  this.$message.error("系统繁忙，请稍后再试");
                } else if (r.data.code == 704) {
                  this.$message.error("登录失效，请重新登录");
                }
              });
            } else {
              this.$message.warning(row.account + "已为正常状态");
            }
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    selectable(row, index) {
      if (row.id == 1) {
        return false;
      } else {
        return true;
      }
    },
    formatRole(row, column, cellValue) {
      for (const role of this.roles) {
        if (cellValue == role.id) {
          return role.name;
        }
      }
    },
    formatStatus(row, column, cellValue) {
      if (cellValue == "1") {
        return "正常";
      } else if (cellValue == "2") {
        return "冻结";
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleCurrentChange(val) {
      Axios.get("/tfss/admin/listByPage", {
        params: {
          account: this.admin.account,
          roleId: this.admin.roleId,
          createDate: this.admin.createDate,
          status: this.admin.status,
          page: val,
        },
        paramsSerializer: (params) => {
          return Qs.stringify(params, { indices: false });
        },
      }).then((r) => {
        if (r.data.code == 200) {
          this.tData = r.data.data.records;
          this.totalNum = r.data.data.total;
          this.page = val;
        } else if (r.data.code == 403) {
          this.$message.error("没有权限");
        } else if (r.data.code == 703) {
          this.$message.error("未登录");
        } else if (r.data.code == 500) {
          this.$message.error("系统繁忙，请稍后再试");
        } else if (r.data.code == 704) {
          this.$message.error("登录失效，请重新登录");
        }
      });
    },
  },
};
</script>

<style scoped>
.el-header,
.el-footer {
  /* background-color: #b3c0d1; */
  color: #333;
  /* text-align: center; */
  line-height: 60px;
}
.el-main {
  /* background-color: #e9eef3; */
  color: #333;
  /* text-align: center; */
  /* line-height: 160px; */
}
</style>